package com.baihan.angus.app.game.busshow.ui.user.upgrade.issuer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baihan.angus.app.game.basic.base.BaseActivity;
import com.baihan.angus.app.game.basic.utils.AppUtil;
import com.baihan.angus.app.game.basic.utils.ComUtil;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.basic.utils.regex.RegexUtils;
import com.baihan.angus.app.game.busshow.BR;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.databinding.ActivityIssuerSecondBinding;
import com.baihan.angus.app.game.busshow.pop_dialog.SelectPicDialog;
import com.baihan.angus.app.game.common.arouter_path.ArouterAppPath;
import com.baihan.angus.app.game.common.bean.response.UpgradeResponse;
import com.baihan.angus.app.game.common.bean.response.Userinfo;
import com.baihan.angus.app.game.common.bean.response.VerifyDetailResponse;
import com.baihan.angus.app.game.common.configs.UserConfig;
import com.baihan.angus.app.game.common.util.PhotoUtil;
import com.baihan.angus.app.game.common.util.imagepickerhelper.ImageOperateHelper;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lcw.library.imagepicker.ImagePicker;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 升级发行信息上传
 */
@Route(path = ArouterAppPath.ISSUER_SECOND_ACTIVITY)
public class IssuerSecondActivity extends BaseActivity<ActivityIssuerSecondBinding, IssuerSecondVM> {

    @Autowired(name = "verifyId")
    String verifyId;

    private Userinfo userinfo;

    private SelectPicDialog mSelectPicDialog;

    private Map<String, Object> mUpgradeRequest = new HashMap<>();

    public final static String ISSUER_TAG_FRONT = "issuer_front";
    public final static String ISSUER_TAG_BACK = "issuer_back";
    public final static String ISSUER_TAG_LICENSE = "issuer_license";
    public final static String ISSUER_TAG_LOGO = "issuer_logo";
    public String currentTag;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_issuer_second;
    }

    @Override
    protected int getViewModelId() {
        return BR.issuerSecondVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        userinfo = UserConfig.getUserConfig().getUser();

        mVDBinding.titleView.setLeftOnClickListener(view -> finish());
        mVDBinding.rootView.showLoading();

        mVDBinding.ivFrontPic.setOnClickListener(view -> {
            uploadPic();
            currentTag = ISSUER_TAG_FRONT;
        });

        mVDBinding.ivBackPic.setOnClickListener(view -> {
            uploadPic();
            currentTag = ISSUER_TAG_BACK;
        });

        mVDBinding.ivLicensePic.setOnClickListener(view -> {
            uploadPic();
            currentTag = ISSUER_TAG_LICENSE;
        });

        mVDBinding.ivLogoPic.setOnClickListener(view -> {
            uploadPic();
            currentTag = ISSUER_TAG_LOGO;
        });

        mVDBinding.tvSubmit.setOnClickListener(view -> {
            String issuerName = mVDBinding.etIssuerName.getText().toString();
            String company = mVDBinding.etCompanyAddr.getText().toString();
            String phone = mVDBinding.etPhone.getText().toString();
            String wechat = mVDBinding.etWechat.getText().toString();
            if (ComUtil.hasEmpty(issuerName, company, phone, wechat, mViewModel.ofFrontUrl.get(),
                    mViewModel.ofBackUrl.get(), mViewModel.ofLicenseUrl.get())) {
                Tooast.normalInfo("请将资料补全");
            } else if (!RegexUtils.isMobileSimple(phone)) {
                Tooast.normalInfo(getString(R.string.phoneIsWrong));
            } else {
                if (mVDBinding.tvSubmit.getText().equals(getString(R.string.submit))) {
                    upgrade();
                } else if (mVDBinding.tvSubmit.getText().equals(getString(R.string.reSubmit))) {
                    updateUpgrade();
                }
            }
        });
    }

    @Override
    protected void initData() {
        mViewModel.getVerifyDetail(verifyId, userinfo.getUser_id());
    }

    private void upgrade() {
        mUpgradeRequest.put("type", 3);//3发行 4店家 5DM 6编剧
        mUpgradeRequest.put("name", mVDBinding.etIssuerName.getText().toString());
        mUpgradeRequest.put("address", mVDBinding.etCompanyAddr.getText().toString());
        mUpgradeRequest.put("id_front_pic", mViewModel.ofFrontUrl.get());
        mUpgradeRequest.put("id_back_pic", mViewModel.ofBackUrl.get());
        mUpgradeRequest.put("license_pic", mViewModel.ofLicenseUrl.get());
        mUpgradeRequest.put("logo_pic", mViewModel.ofLogoUrl.get());
        mUpgradeRequest.put("mobile", mVDBinding.etPhone.getText().toString());
        mUpgradeRequest.put("wechat", mVDBinding.etWechat.getText().toString());
        mViewModel.upgrade(mUpgradeRequest);
    }

    private void updateUpgrade() {
        mUpgradeRequest.put("type", 3);//3发行 4店家 5DM 6编剧
        mUpgradeRequest.put("name", mVDBinding.etIssuerName.getText().toString());
        mUpgradeRequest.put("address", mVDBinding.etCompanyAddr.getText().toString());
        mUpgradeRequest.put("id_front_pic", mViewModel.ofFrontUrl.get());
        mUpgradeRequest.put("id_back_pic", mViewModel.ofBackUrl.get());
        mUpgradeRequest.put("license_pic", mViewModel.ofLicenseUrl.get());
        mUpgradeRequest.put("logo_pic", mViewModel.ofLogoUrl.get());
        mUpgradeRequest.put("mobile", mVDBinding.etPhone.getText().toString());
        mUpgradeRequest.put("wechat", mVDBinding.etWechat.getText().toString());
        mViewModel.updateUpgrade(verifyId, mUpgradeRequest);
    }

    @Override
    protected void initObservers() {
        super.initObservers();

        mViewModel.mldDetail.observe(this, new Observer<VerifyDetailResponse.Data>() {
            @Override
            public void onChanged(VerifyDetailResponse.Data data) {
                if (null != data) {
                    showContent(data);
                } else {
                    mVDBinding.rootView.showContent();
                }
            }
        });

        mViewModel.mldUpgrade.observe(this, new Observer<UpgradeResponse.Data>() {
            @Override
            public void onChanged(UpgradeResponse.Data data) {
                if (null != data) {
                    Tooast.normalInfo("提交成功");
                    mViewModel.getUserInfo();
                    finish();
                }
            }
        });

        mViewModel.mldUpdateUpgrade.observe(this, new Observer<UpgradeResponse.Data>() {
            @Override
            public void onChanged(UpgradeResponse.Data data) {
                if (null != data) {
                    Tooast.normalInfo("提交成功");
                    mViewModel.getUserInfo();
                    finish();
                }
            }
        });
    }

    public void showContent(VerifyDetailResponse.Data data) {
        mVDBinding.rootView.showContent();
//        mVDBinding.rlAuth.setVisibility(View.VISIBLE);
        setData();
        if (data.getVerify_status() == 1) {
            setEnable(false);
            mVDBinding.llVerify.setVisibility(View.VISIBLE);
            mVDBinding.tvVerifyStatus.setText("正在审核中");
            mVDBinding.tvVerifyStatus.setTextColor(getColor(R.color.textColor35));

            mVDBinding.llSubmit.setVisibility(View.GONE);
        } else if (data.getVerify_status() == 2) {
            mVDBinding.llVerify.setVisibility(View.VISIBLE);
            mVDBinding.tvVerifyStatus.setText("已认证");
            mVDBinding.tvVerifyStatus.setTextColor(getColor(R.color.textColor34));

            mVDBinding.llSubmit.setVisibility(View.VISIBLE);

            setEnable(true);
        } else if (data.getVerify_status() == 3) {
            mVDBinding.llVerify.setVisibility(View.VISIBLE);
            mVDBinding.tvVerifyStatus.setText("认证失败");
            mVDBinding.tvVerifyStatus.setTextColor(getColor(R.color.textColor33));

            mVDBinding.llSubmit.setVisibility(View.VISIBLE);
            mVDBinding.tvSubmit.setText(getString(R.string.reSubmit));
            setEnable(true);
        }
    }

    public void setData() {
        mVDBinding.etIssuerName.setText(mViewModel.mldDetail.getValue().getName());
        mVDBinding.etCompanyAddr.setText(mViewModel.mldDetail.getValue().getAddress());
        mVDBinding.etPhone.setText(mViewModel.mldDetail.getValue().getMobile());
        mVDBinding.etWechat.setText(mViewModel.mldDetail.getValue().getWechat());

        mViewModel.ofFrontUrl.set(mViewModel.mldDetail.getValue().getId_front_pic());
        mViewModel.ofBackUrl.set(mViewModel.mldDetail.getValue().getId_back_pic());
        mViewModel.ofLicenseUrl.set(mViewModel.mldDetail.getValue().getLicense_pic());
        mViewModel.ofLogoUrl.set(mViewModel.mldDetail.getValue().getLogo_pic());
    }

    public void setEnable(boolean isEnable) {
        mVDBinding.etIssuerName.setEnabled(isEnable);
        mVDBinding.etPhone.setEnabled(isEnable);
        mVDBinding.etCompanyAddr.setEnabled(isEnable);
        mVDBinding.etWechat.setEnabled(isEnable);
        mVDBinding.ivFrontPic.setEnabled(isEnable);
        mVDBinding.ivBackPic.setEnabled(isEnable);
        mVDBinding.ivLicensePic.setEnabled(isEnable);
        mVDBinding.ivLogoPic.setEnabled(isEnable);
    }

    private void uploadPic() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(List<String> permissionsGranted) {
                showDialog();
            }

            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                ToastUtils.showShort(R.string.open_permission);
            }
        }).request();
    }

    private void showDialog() {
        if (null == mSelectPicDialog) {
            mSelectPicDialog = new SelectPicDialog(this, new SelectPicDialog.Callback() {
                @Override
                public void onTakePhoto() {
                    PhotoUtil.openCameraImage(IssuerSecondActivity.this);
                    mSelectPicDialog.dismiss();
                }

                @Override
                public void onAlbum() {
                    startImageLib();
                    mSelectPicDialog.dismiss();
                }
            });
        }
        mSelectPicDialog.show();
    }

    private void startImageLib() {
        ImageOperateHelper.startImagePicker(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageOperateHelper.REQUEST_SELECT_IMAGES_CODE) {
            if (resultCode == RESULT_OK) {
                List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                Luban.with(this).load(imagePaths.get(0))
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.uploadFile(file, currentTag);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo(getString(R.string.compassPicFail));

                            }
                        }).launch();
            }
        } else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
            if (resultCode == RESULT_OK) {
                File imageFile;
                imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
                Luban.with(this).load(imageFile)
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.uploadFile(file, currentTag);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo(getString(R.string.compassPicFail));

                            }
                        }).launch();
            }
        }
    }
}